<template>
    <view class="wrap">
        <view class="top-wrap flex flex-column">
            <view class="my-works flex flex-column flex-v-center " @click="goroMyWorks">
                <image src="@/pages/minePages/static/cloudAlbum/my-works.png" mode="" class="u-m-16"></image>
                <view class="">我的作品</view>
            </view>
            <view class="title">云相册</view>
        </view>
        <!-- 相册列表 -->
        <AlbumList
            :photosList="photosList"
            :menuStatus="showMenu"
            :scrollHight="scrollHeight"
            :showSelectItem="showMenu && (currentMenuType === 'downLoad' || currentMenuType === 'delect')"
            @selectedPhotos="getSelectedPhotos"
            @gotoPreView="gotoPreView"
        ></AlbumList>
        <!-- 底部删除按钮 -->
        <view class="btns btns-delect" v-if="showMenu && currentMenuType === 'delect'">
            <view class="cancel" @click="cancel">取消</view>
            <view class="delect" @click="delectPhotos">删除({{ selectedDeleteAmount }})</view>
        </view>
        <view class="btns btns-downLoad" v-if="showMenu && currentMenuType === 'downLoad'" @click="savePhotos">保存到相册</view>
        <!-- 圆形菜单 -->
        <view class="circle-menu-wrap"><CircleMenu :menuStatus="showMenu" @emitMenuStatus="getMenuStatus" @emitSelectMenuItem="selectMenuItem"></CircleMenu></view>
    </view>
</template>
<script>
import CircleMenu from '@/components/CircleMenu/index.vue';
import AlbumList from './components/AlbumList.vue';
import { getAlbumPhotoes, deleteAlbumPhoto } from '@/api/photos.js';
import { uploadFile } from '@/common/utils.js';
export default {
    name: '',
    data() {
        return {
            showMenu: false,
            // 当前选中的menu
            currentMenuType: '',
            // 图片列表数据
            photosList: [],
            // 待上传照片数量
            tobeUploadAmount: 0,
            // 上传成功数量
            uploadSuccessAmount: 0,
            // 上传失败数量
            uploadErrorAmount: 0,
            // 待下载图片路径
            downLoadArr: [],
            // 待保存到相册的图片数量
            tobeSaveAmount: 0,
            // 保存到相册成功的数量
            saveSuccessAmount: 0,
            // 保存到相册失败的数量
            saveErrorAmount: 0,
            // 选择的待删除的照片数量
            selectedDeleteAmount: 0,
            // 删除图片的列表
            deleteArr: [],
            // 列表高度
            scrollHeight: '500px'
        };
    },
    computed: {},
    onLoad() {
        this.getAlbumPhotoes();
    },
    onShow() {},
    mounted() {
        this.getScrollHeight();
    },
    methods: {
        // 查看我的作品
        goroMyWorks() {
            this.$u.route('/pages/compoundPages/works/works');
        },
        async getScrollHeight() {
            let systemInfo = await this.$uniPromise.getSystemInfo();
            if (this.showMenu && (this.currentMenuType === 'downLoad' || this.currentMenuType === 'delect')) {
                this.scrollHeight = systemInfo.windowHeight - uni.upx2px(258 + 98) + 'px';
            } else {
                this.scrollHeight = systemInfo.windowHeight - uni.upx2px(258) + 'px';
            }
            console.log(this.scrollHeight);
        },
        // 获取相册数据
        async getAlbumPhotoes() {
            this.photosList = await getAlbumPhotoes();
            if (this.photosList.length > 0) {
                this.initPhotosList();
            }
        },
        // 初始化照片数据
        initPhotosList() {
            this.photosList.forEach(item => {
                item.photos.forEach(item2 => {
                    item2.selected = false;
                    item2.imageId = this.$u.guid(20);
                });
            });
        },
        // 获取menu状态
        getMenuStatus(status) {
            this.showMenu = status;
            this.getScrollHeight();
        },
        // 选择menu
        selectMenuItem(type) {
            this.currentMenuType = type;
            this.getScrollHeight();
            if (type === 'refresh') {
                this.getAlbumPhotoes();
            }
            if (type === 'upload') {
                this.uploadPhotos();
            }
            if (type === 'downLoad') {
            }
            if (type === 'delect') {
                this.selectedDeleteAmount = this.getSelectedPhotosArr().length;
            }
        },
        // 从相册选取照片
        async uploadPhotos() {
            let photos = await this.$uniPromise.chooseImage();
            if (photos && photos.tempFilePaths.length > 0) {
                this.tobeUploadAmount = photos.tempFilePaths.length;
                this.startUpload(photos.tempFilePaths);
            }
        },
        // 开始上传照片
        startUpload(list) {
            setTimeout(() => {
                uni.showLoading({
                    title: '上传中',
                    mask: true
                });
            }, 500);
            list.forEach((item, index) => {
                uploadFile(`${this.$config.baseUrl}/api/upload/obs`, item, this.$config.tokenKey, {}, true)
                    .then(res => {
                        if (res.RequestStatus === 100 && res.Data && res.Data.image_url) {
                            this.uploadSuccessAmount += 1;
                        } else {
                            this.uploadErrorAmount += 1;
                        }
                        this.checkUploadEnd();
                    })
                    .catch(err => {
                        this.uploadErrorAmount += 1;
                        this.checkUploadEnd();
                    });
            });
        },
        //判断是否全部上传完成
        checkUploadEnd() {
            if (this.uploadSuccessAmount + this.uploadErrorAmount >= this.tobeUploadAmount) {
                uni.hideLoading();
                this.$showToast(`上传成功${this.uploadSuccessAmount}张,上传失败${this.uploadErrorAmount}张`);
                this.uploadSuccessAmount = this.uploadErrorAmount = this.tobeUploadAmount = 0;
                this.getAlbumPhotoes();
            }
        },
        //获取选择的所有照片数据 更新照片列表
        getSelectedPhotos(list) {
            this.photosList = list;
            this.selectedDeleteAmount = this.getSelectedPhotosArr().length;
        },
        // 取消
        cancel() {
            this.showMenu = false;
            this.currentMenuType = '';
            this.initPhotosList();
            this.getScrollHeight();
        },
        // 获取所有选中的照片
        getSelectedPhotosArr() {
            let tempArr = [];
            this.photosList.forEach(item => {
                item.photos.forEach(item2 => {
                    if (item2.selected) {
                        tempArr.push(item2);
                    }
                });
            });
            return tempArr;
        },
        // 删除照片
        delectPhotos() {
            if (this.selectedDeleteAmount <= 0) {
                this.$showToast('请选择要删除的照片');
                return;
            }
            this.deleteAlbumPhoto();
        },
        // 删除照片
        async deleteAlbumPhoto() {
            this.deleteArr = this.$u.deepClone(this.getSelectedPhotosArr());
            let deleteIds = this.getIdsToString(this.deleteArr, 'albumid');
            let result = await deleteAlbumPhoto({
                ids_json: deleteIds
            });
            if (result.RequestStatus === 100) {
                this.getAlbumPhotoes();
                this.selectedDeleteAmount=0
            }
        },
        getIdsToString(list, key) {
            let tempList = [];
            list.forEach((item, index) => {
                tempList.push(item[key]);
            });
            return JSON.stringify(tempList);
        },
        // 保存到相册
        savePhotos() {
            this.downLoadArr = this.getSelectedPhotosArr();
            if (this.downLoadArr.length <= 0) {
                this.$showToast('请选择要保存的照片');
                return;
            }
            uni.showLoading({
                title: '图片正在保存中....',
                mask: true
            });
            this.tobeSaveAmount = this.downLoadArr.length;
            this.downLoadArr.forEach(item => {
                this.loadFile(item.image_url);
            });
        },
        // 下载和保存照片
        async loadFile(url) {
            let isTrueDomain = this.$config.domainPath.some(item => {
                return url.includes(item);
            });
            if (isTrueDomain) {
                try {
                    let tempPath = await this.$uniPromise.downloadFile({ url: url });
                    try {
                        await this.$uniPromise.saveImageToPhotosAlbum({ filePath: tempPath.tempFilePath });
                        this.$showToast('保存成功');
                        this.saveSuccessAmount += 1;
                        this.checkSaveToPhotosAlbumEnd();
                    } catch (err) {
                        this.$showToast('保存失败');
                        this.saveErrorAmount += 1;
                        this.checkSaveToPhotosAlbumEnd();
                    }
                } catch (err) {
                    this.$showToast('图片下载失败，请检查网络状况！');
                    this.saveErrorAmount += 1;
                    this.checkSaveToPhotosAlbumEnd();
                }
            } else {
                this.$showToast('图片地址不在合法域名之内！');
                this.saveErrorAmount += 1;
                this.checkSaveToPhotosAlbumEnd();
            }
        },
        // 监测是否全部保存完  包括保存失败的
        checkSaveToPhotosAlbumEnd() {
            if (this.saveSuccessAmount + this.saveErrorAmount >= this.tobeSaveAmount) {
                uni.hideLoading();
                this.saveSuccessAmount = this.saveErrorAmount = this.tobeSaveAmount = 0;
                this.downLoadArr = [];
            }
        },
        // 预览页面
        gotoPreView(target) {
            this.$u.vuex('vuex_myPhotosList', this.photosList);
            this.$u.route('/pages/minePages/lookMyPhotos/lookMyPhotos', {
                targetId: target.imageId
            });
        }
    },
    watch: {},
    components: {
        CircleMenu,
        AlbumList
    }
};
</script>
<style lang="scss" scoped>
.wrap {
    background: #fff;
    min-height: 100vh;
    max-height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    .my-works {
        padding: 30rpx 30rpx 0;
        align-self: flex-start;
        image {
            width: 42rpx;
            height: 40rpx;
        }
    }
    .title {
        font-size: 36rpx;
        padding: 50rpx 30rpx 30rpx;
        line-height: 36rpx;
        font-weight: bold;
    }

    .btns {
        position: fixed;
        left: 0;
        bottom: 0;
        width: 750rpx;
        height: 98rpx;
        background-color: #ffffff;
        box-shadow: 0rpx -6rpx 40rpx 0rpx rgba(0, 0, 0, 0.05);
        flex-shrink: 0;
        display: flex;
        justify-content: space-around;
        align-items: center;
        font-size: 30rpx;
        line-height: 30rpx;
    }
    .btns-delect {
        .cancel,
        .delect {
            width: 50%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .delect {
            color: #ff6060;
        }
    }
    .btns-downLoad {
        color: #20bf64;
    }
    .circle-menu-wrap {
        position: fixed;
        right: 30rpx;
        bottom: 180rpx;
        width: 90rpx;
        height: 90rpx;
        z-index: 66;
    }
}
</style>
